﻿@using Abp.Application.Navigation;
@inherits LayoutComponentBase
@inject SessionAppService sessionService
@*@inject IServiceProvider services*@
@inject IUnitOfWorkManager uowManager
@inject IUserNavigationManager abpNavManager
@inject NavigationManager blazorNavManager
@implements IDisposable

<PageTitle>元凯客服平台</PageTitle>

<MudThemeProvider Theme="MyCustomTheme" />
<MudDialogProvider />
<MudSnackbarProvider />

<MudLayout>
    <MudAppBar>
        <MudIconButton Icon="@Icons.Material.Filled.Menu" Edge="Edge.Start" OnClick="@((e) => DrawerToggle())" />
        <MudBreadcrumbs Items="_items"></MudBreadcrumbs>
        <MudSpacer />
        <MudStack Row>
            <MudHidden Breakpoint="@Breakpoint.Xs">
            <MudText Style="padding-top:.7rem; "  Typo="Typo.body2">@appSession?.Customer?.Name</MudText>
            </MudHidden>
            <MudMenu FullWidth="false" Dense ActivationEvent="MouseEvent.MouseOver" AnchorOrigin="Origin.BottomCenter" TransformOrigin="Origin.TopCenter">
                <ActivatorContent>
                    <MudChip Icon="@Icons.Material.Filled.Person">@appSession?.User?.Name</MudChip>
                </ActivatorContent>
                <ChildContent>
                    <MudMenuItem>我的资料</MudMenuItem>
                    <MudMenuItem><a href="/account/logout?appKey=cust">退出系统</a></MudMenuItem>
                </ChildContent>
            </MudMenu>
        </MudStack>
    </MudAppBar>
     <MudDrawer @bind-Open="@_drawerOpen" Width="12rem;" Variant="@DrawerVariant.Mini" OpenMiniOnHover="true">
         <MudDrawerHeader Class="mud-theme-primary" Style="padding:12px 0 0 12px; width:12rem;">
             @if (_drawerOpen)
            {
                <MudStack Row Spacing="2">
                     <MudIcon Icon="@Icons.Custom.Brands.Discord" Color="Color.Surface" Size="Size.Large" />
                     <MudText Align="Align.Center" Typo="Typo.h6" Style="line-height:2.2rem;">
                         @if (_drawerOpen)
                        {
                            @:小管印
                        }
                    </MudText>
                </MudStack>
            }
            else
            {
                <MudIcon Icon="@Icons.Custom.Brands.Discord" Color="Color.Surface" Size="Size.Large" />
            }
        </MudDrawerHeader>
        @*<MudDrawerContainer>
        士大夫地方
        </MudDrawerContainer>*@
        <MudNavMenu Margin="Margin.Normal" Color="Color.Surface" Bordered="true" Dense="false">
            @* <MudNavLink Href="/admin" Match="NavLinkMatch.All" Icon="@Icons.Material.Outlined.Home">控制台</MudNavLink> *@
            @if (menu != null)
            {
                foreach (var item in menu.Items)
                {
                    @if (item.Items != default && item.Items.Any())
                    {
                        <MudNavGroup Title="@(_drawerOpen?item.DisplayName:string.Empty)" Style="width:12rem;" Icon="@item.Icon" HideExpandIcon="@(!_drawerOpen)">

                            @foreach (var item2 in item.Items)
                            {
                                <MudNavLink Href="@item2.Url" Match="NavLinkMatch.All" Icon="@item2.Icon" Style="width:12rem;">
                                    @if (_drawerOpen)
                                    {
                                        @item2.DisplayName
                                    }
                                </MudNavLink>
                            }
                        </MudNavGroup>
                    }
                    else
                    {
                        <MudNavLink Href="@item.Url" Match="NavLinkMatch.All" Icon="@item.Icon" Style="width:12rem;">
                            @if (_drawerOpen)
                            {
                                @item.DisplayName
                            }
                        </MudNavLink>
                    }
                }
            }
        </MudNavMenu>
    </MudDrawer>
    <MudMainContent Style="height:100%;">
        <ErrorBoundary>
            <ChildContent>
                <MudContainer MaxWidth="@MaxWidth.False" Style="padding:1rem;  position:relative; height:100%;">
                    @Body
                </MudContainer>
            </ChildContent>
            <ErrorContent>
                <p class="errorUI">服务端发生未处理异常！请联系系统管理员。 @context.StackTrace</p>
                <p class="errorUI"> @context.Message</p>
                <p class="errorUI">@context.StackTrace</p>
            </ErrorContent>
        </ErrorBoundary>
    </MudMainContent>
</MudLayout>
@code {
    
    MudTheme MyCustomTheme = new MudTheme()
        {
            Palette = new Palette()
            {
                Primary = Colors.Blue.Darken3,
                Background = Colors.Grey.Lighten4,
                //Secondary = Colors.Green.Accent4,
                AppbarBackground = Colors.Shades.White,
                AppbarText = Colors.Green.Darken4,
                DrawerBackground = Colors.Blue.Darken4,
                DrawerIcon = Colors.Blue.Lighten5,
                DrawerText = Colors.Blue.Lighten5
            },
            //PaletteDark = new PaletteDark()
            //{
            //    Primary = Colors.Blue.Lighten1
            //},
            //LayoutProperties = new LayoutProperties()
            //{
            //    DrawerWidthLeft = "260px",
            //    DrawerWidthRight = "300px"
            //}
        };

    bool _drawerOpen = true;
    GetCurrentLoginInformationsOutput appSession;//=new GetCurrentLoginInformationsOutput();
    void DrawerToggle()
    {
        _drawerOpen = !_drawerOpen;
    }
    UserMenu menu;
    private List<BreadcrumbItem> _items = new List<BreadcrumbItem>();

    protected override void OnInitialized()
    {
        blazorNavManager.LocationChanged += HandleLocationChanged;
    }

    //[UnitOfWork(false)] 手动刷新执行两次，用这个好像也会出问题，还是代码内部手动开启吧
    //https://learn.microsoft.com/zh-cn/aspnet/core/blazor/components/lifecycle?view=aspnetcore-7.0#stateful-reconnection-after-prerendering
    protected override async Task OnInitializedAsync()
    {
        //f5刷新时，此时可能出现工作单元释放，最终导致事务不生效，所以init中必须手动开启事务
        using var scope = uowManager.Begin(new UnitOfWorkOptions { IsTransactional = false });
        appSession = (await sessionService.GetCurrentLoginInformations()) as GetCurrentLoginInformationsOutput;
        if (appSession.User != default)
        {
            menu = await abpNavManager.GetMenuAsync(PermissionNames.Customer, new Abp.UserIdentifier(appSession.Tenant.Id, appSession.User.Id));
        }
    }

    private void HandleLocationChanged(object? sender, LocationChangedEventArgs e)
    {
        var curr = this.menu.Items.SingleOrDefault(c => e.Location.EndsWith(c.Url, StringComparison.OrdinalIgnoreCase));
        if (curr == default)
            return;
        this._items = new List<BreadcrumbItem> { new BreadcrumbItem(curr.DisplayName, curr.Url) };
        StateHasChanged();
    }
    public void Dispose()
    {
        blazorNavManager.LocationChanged -= HandleLocationChanged;
    }
}